<template>
  <div>
    <!-- Header -->
    <div>
      <TitleCompound :title="title"></TitleCompound>
    </div>

    <!-- Content -->
    <div>
      <p>
        <b>computed</b>，请参考<a href="https://cn.vuejs.org/api/reactivity-core.html#computed">computed</a>
      </p>
      <ul>
        <li>其接受一个getter函数，返回一个只读的响应式的 <b>ref</b>对象。</li>
        <li>也可以接受一个带有<b>get</b>和<b>set</b>函数的对象来创建一个可写的ref对象。</li>
      </ul>
      <p>其结果会缓存，即在引用未变的情况下，多次调用，也只会调用一次。</p>
      <!-- getter函数 -->
      <div>
        <h2>getter函数</h2>
        <h3>Total: {{ sum }}</h3>
        <el-button @click="sum++" type="primary">Add, 请查看console log 调用日志</el-button>
        <h2>Double: {{ double }}</h2>
        <h2>Double: {{ double }}</h2>
        <h2>Double: {{ double }}</h2>
        <h2>Double: {{ double }}</h2>
        <h2>Double: {{ double }}</h2>
      </div>

      <!-- get和set函数 -->
      <div>
        <h2>get和set函数</h2>
        <p>Person 信息</p>
        <el-table :data="[person]" border>
          <el-table-column prop="name" label="Name"></el-table-column>
          <el-table-column prop="age" label="Age"></el-table-column>
          <el-table-column prop="gender" label="Gender"></el-table-column>
        </el-table>
        <div class="computedlarge">其 Birth Year: {{ birthYear }}</div>
        <p class="computedlarge1">其 Birth Year: {{ birthYear }}</p>
        <p class="computedlarge2">其 Birth Year: {{ birthYear }}</p>
        <p class="computedlarge3">其 Birth Year: {{ birthYear }}</p>
        <el-button @click="birthYear--" type="primary">Add one year [通过birthYear-- 来实现修改Person的年龄信息]
        </el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import TitleCompound from '@/components/TitleCompound.vue'
import type { Person } from '@/types'
import { computed, ref } from 'vue'

const title = 'Computed Quickstart'

const sum = ref(0)

const double = computed(() => {
  console.log('computed double')
  return sum.value * 2
})

// get and set
const person = ref<Person>({
  name: 'John',
  age: 20,
  gender: 'male',
})

const birthYear = computed({
  get() {
    return new Date().getFullYear() - person.value.age
  },
  set(value) {
    person.value.age = new Date().getFullYear() - value
  },
})
</script>

<style lang="scss" scoped>
$font-size: x-large;

.computedlarge {
  font-size: $font-size;
  color: cadetblue;
}

.computedlarge1 {
  font-size: $font-size;
  color: antiquewhite;
}

.computedlarge2 {
  font-size: $font-size;
  color: aquamarine;
}

.computedlarge3 {
  font-size: $font-size;
  color: burlywood;
}
</style>
